import { Component, forwardRef, Input, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
	selector: 'pay-password',
	template: `
		<div class="pay-password-box">
			<input type="tel" #element [ngModel]="password" (input)="change($event)" />
			<i [ngClass]="{ active: password.length > 0 }"><img src="../../assets/images/usercenter/input.jpg"/></i>
			<i [ngClass]="{ active: password.length > 1 }"><img src="../../assets/images/usercenter/input.jpg"/></i>
			<i [ngClass]="{ active: password.length > 2 }"><img src="../../assets/images/usercenter/input.jpg"/></i>
			<i [ngClass]="{ active: password.length > 3 }"><img src="../../assets/images/usercenter/input.jpg"/></i>
			<i [ngClass]="{ active: password.length > 4 }"><img src="../../assets/images/usercenter/input.jpg"/></i>
			<i [ngClass]="{ active: password.length > 5 }"><img src="../../assets/images/usercenter/input.jpg"/></i>
		</div>
	`,
	styles: [
		`
			.pay-password-box {
				margin-top: 3rem;
				display: flex;
				justify-content: space-between;
				position: relative;
			}
			.pay-password-box input {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				border: none;
				background: none;
				z-index: 9;
				opacity: 0;
			}
			.pay-password-box i {
				display: block;
				width: 15%;
				position: relative;
				background:#6F7275;
				border-radius:0.4rem;
			}
			.pay-password-box i img {
				width: 100%;
				display: block;
				opacity: 0;
			}
			.pay-password-box i.active:after {
				content: '';
				width: 1.2rem;
				height: 1.2rem;
				border-radius: 0.6rem;
				background: #fff;
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
			}
		`,
	],
	providers: [
		{
			provide: NG_VALUE_ACCESSOR,
			useExisting: forwardRef(() => PayPasswordComponent),
			multi: true,
		},
	],
})
export class PayPasswordComponent implements OnInit, ControlValueAccessor {
	@Input()
	password = '';
	constructor() {
	}
	ngOnInit() {}
	propagateChange = (_: any) => {};
	registerOnChange(fn: any) {
		this.propagateChange = fn;
	}
	registerOnTouched(fn: any) {}
	writeValue(value: string) {
		this.password = value || '';
	}
	change(e) {
		const value = e.target.value;
		this.password = value.replace(/[^0-9]/gi, '');
		if (this.password.length > 6) {
			this.password = this.password.substring(0, 6);
		} else if (this.password.length === 6) {
			e.target.blur();
		}
		e.target.value = this.password;
		this.propagateChange(this.password);
	}
}
